//
//  MineController.swift
//  HappyEat
//
//  Created by ctx2016 on 17/1/6.
//  Copyright © 2017年 陌路是我. All rights reserved.
//

import UIKit
import SwiftyJSON

class MineController: UIViewController ,UITableViewDelegate,UITableViewDataSource{
    let Style0CellId = "Style0Id"
    let Style1CellId = "Style1Id"
    let Style2CellId = "Style2Id"
    let userDefault:UserDefaults = UserDefaults.standard
    let titles:[String] = ["邀请好友","优惠券","消息中心","分享软件","帮助中心","充值记录","联系客服","商家合作"]
    let images:[String] = ["yaoqing","youhuiquan","xiaoxi","fenxiang","bangzhu","chongzhi","kefu","hezuo"]
    var tableview:UITableView = UITableView.init()
    var leftButton:UIButton = UIButton.init(frame: CGRect.init(x: 16, y: 0, width: 80, height: 20))
    var headerView:UIView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: k_Wide, height: 140+20))
    let nameLabel:UILabel = UILabel.init()
    var navigationBackGroundView:UIView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: k_Wide, height: 64))
    //网络请求
    var netRequst:NetworkRequest = NetworkRequest.shareInstance
    //字符校验
    var stringTool:CodingStrinTool = CodingStrinTool.shareInstance
    //界面用户model
    var jsonData:JSON?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.createTabView()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.setNavi()
        self.navigationItem.title = ""
        
        self.loadUSerDefaultinfoACtion()
        //获取用户信息
        self.loadUserInfo()
        UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationBackGroundView.removeFromSuperview()
    }
}
extension MineController {
    //MARK:设置Nav
    func setNavi(){
        self.navigationController?.navigationBar.barTintColor = .red
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: self.leftButton)
        self.leftButton.setTitle("id：213123123", for: .normal)
//        self.leftButton.sizeToFit()
        self.leftButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        self.leftButton.setTitle("我是猪脚", for: .normal)
        //添加右边设置按钮
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "", imagStr: "ic_shezhi", fontSize: 15, target: self, action: #selector(barButtonRightAction))
//        let backgroundImage:UIImage =  UIImage.init()
//        self.navigationController?.navigationBar.setBackgroundImage(backgroundImage, for: .default)
        //取消navigationBar下面的背景线条
        self.navigationController?.navigationBar.shadowImage = UIImage.init()
//        //修改status状态颜色为白色
//        self.navigationController?.navigationBar.barStyle = .black
//        //添加一个背景颜色View
//        navigationBackGroundView.backgroundColor = UIColor.red
//        navigationBackGroundView.alpha = 0.0
//        self.navigationController?.navigationBar.subviews.first?.addSubview(navigationBackGroundView)
        self.navigationController?.navigationBar.tintColor = .white
        //解决无故偏移
        self.automaticallyAdjustsScrollViewInsets = false
    }
    //MARK:LOAD USERDEFAULTINFO
    func loadUSerDefaultinfoACtion(){
        guard let nameStr:String = self.userDefault.object(forKey:NICKNAME) as! String? else{
            self.nameLabel.isUserInteractionEnabled = true
            self.nameLabel.text = "注册/登录"
            self.leftButton.setTitle("我是猪脚", for: .normal)
            return
        }
        self.nameLabel.isUserInteractionEnabled = false
        self.leftButton.setTitle(nameStr, for: .normal)
        self.nameLabel.text = nameStr
    }
    //MARK:进入界面刷新数据
    func loadUserInfo(){
        //        post参数：productSeriesId：该期商品id
        guard let phoneNum:String = UserDefaults.standard.object(forKey: PHONE) as! String? else{
            return
        }
        let passWord:String = UserDefaults.standard.object(forKey: PASSWWORD) as! String? ?? ""
        var miStr:String = phoneNum + ":" + passWord
        miStr = self.stringTool.base64Encoding(plainString: miStr)
        let parmas:[String:String] = ["":""]
        self.netRequst.postRequest(urlString: GetUserInfo_URL, params: parmas, headerStr: miStr, success: { [weak self](success) in
            let returnDic = JSON(success)
            if returnDic["status"] == "SUCCESS" {
             self?.jsonData = returnDic["data"]
                let indexPath:IndexPath = IndexPath.init(row: 0, section: 0)
                self?.tableview.reloadRows(at: [indexPath], with: .none)
            }
            })
        { (error) in
            print(error)
        }
    }
    //MARK:按钮左边事件处理
    func barButtonLeftAction(){
        
    }
    //MARK:右边按钮事件处理
    func barButtonRightAction(){
        let vc:MineSetController = MineSetController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    //MARK:创建tableview
    func createTabView(){
        self.view.addSubview(self.tableview)
        self.tableview.snp.makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(-49)
            make.top.equalTo(64)
        }
//        self.tableview.backgroundColor = .orange
        self.tableview.tableHeaderView = self.headerView
        self.tableview.delegate = self
        self.tableview.dataSource = self
        let headerBgView:UIImageView = UIImageView.init(image: UIImage.init(named: "background_image.jpg"))
        headerBgView.backgroundColor = .red
        self.headerView.addSubview(headerBgView)
        headerBgView.snp.makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(0)
            make.top.equalTo(0)
        }
        headerBgView.contentMode = .scaleToFill
        let iconTx:UIImageView = UIImageView.init()
        iconTx.layer.cornerRadius = 37.5
        self.headerView.addSubview(iconTx)
        iconTx.snp.makeConstraints { (make) in
            make.left.equalTo((k_Wide - 75)/2)
            make.top.equalTo(40)
            make.size.equalTo(CGSize.init(width: 75, height: 75))
        }
        iconTx.backgroundColor = .black
        
        
        self.headerView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(16)
            make.top.equalTo(iconTx.snp.bottom).offset(8)
        }
        nameLabel.textAlignment = .center
        nameLabel.text = "注册/登录"
        nameLabel.textColor = .white
        nameLabel.font = UIFont.systemFont(ofSize: 16)
        nameLabel.isUserInteractionEnabled = true
        let logTap:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(loginAction))
        nameLabel.addGestureRecognizer(logTap)
        self.tableview.separatorStyle = .none
        self.tableview.register(MineStyle0Cell.self, forCellReuseIdentifier: Style0CellId)
        self.tableview.register(MineStyle1Cell.self, forCellReuseIdentifier: Style1CellId)
        self.tableview.register(MineStyle2Cell.self, forCellReuseIdentifier: Style2CellId)
    }
    //MARK:loginAction()
    func loginAction(){
        let vc:MineLoginController = MineLoginController()
        self.navigationController?.pushViewController(vc, animated: false)
    }
    //MARK:tableViewDelegate
    @objc(tableView:didSelectRowAtIndexPath:) func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.row {
        case 1:
            break
        case 2:
            //邀请好友
            let vc:MineShareFriendController = MineShareFriendController()
            self.navigationController!.pushViewController(vc, animated: true)
            break
        case 3:
            //优惠券
            let vc:MineYouHuiJuanController = MineYouHuiJuanController()
            self.navigationController!.pushViewController(vc, animated: false)
            break
        case 4:
            //消息中心
            let vc:MineMessageController = MineMessageController()
            self.navigationController!.pushViewController(vc, animated: true)
            break
        case 5:
            //分享软件
            break
        case 6:
            //帮助中心
            let vc:MineHelpCenterController = MineHelpCenterController()
            self.navigationController?.pushViewController(vc, animated: true)
            break
        case 7:
            //充值记录
            let vc:MineChongZhiController = MineChongZhiController()
            self.navigationController?.pushViewController(vc, animated: true)
            break
        case 8:
            //联系客服
            break
        default:
            //商家合作
            let vc:MineShangJiaController = MineShangJiaController()
            self.navigationController?.pushViewController(vc, animated: true)
           break
        }
    }
    @objc(numberOfSectionsInTableView:) func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    @objc(tableView:cellForRowAtIndexPath:) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.row {
        case 0:
            let cell = MineStyle0Cell.init(style: .default, reuseIdentifier: Style0CellId)
            cell.selectionStyle = .none
            if jsonData != nil{
            cell.jsonData = jsonData
            }
            return cell
        case 1:
            let cell = MineStyle1Cell.init(style: .default, reuseIdentifier: Style1CellId)
            cell.selectionStyle = .none
            return cell
        default:
            let cell = MineStyle2Cell.init(style: .default, reuseIdentifier: Style2CellId)
            cell.selectionStyle = .none
            cell.titleLabel.text = titles[indexPath.row-2]
            cell.iconImageView.image =  UIImage.init(named: images[indexPath.row - 2])
            return cell
        }
    }
    @objc(tableView:heightForRowAtIndexPath:) func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.row {
        case 0:
            return 45
        case 1:
            return 80
        default:
            return 45
        }
    }
    //MARK:滑动触发的代理方法
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.caclulateFrameWithOffSet(scrollView.contentOffset.y)
    }
    func caclulateFrameWithOffSet(_ offSet:CGFloat){
        if offSet >= 140 {
            navigationBackGroundView.alpha = 1.0
        }else{
            navigationBackGroundView.alpha = offSet/140
        }
    }
}
